#include "history.h"
#include <QDebug>

history::history() : db(nullptr) {
    if (!initializeDatabase()) {
        qDebug() << "Failed to initialize history database";
    }
}

history::~history() {
    if (db) {
        sqlite3_close(db);
    }
}

bool history::initializeDatabase() {
    // 打开或创建数据库
    if (sqlite3_open("history.db", &db) != SQLITE_OK) {
        qDebug() << "Can't open database:" << sqlite3_errmsg(db);
        return false;
    }

    // 创建表(如果不存在)
    const QString createTableSQL =
        "CREATE TABLE IF NOT EXISTS history (word TEXT PRIMARY KEY)";

    return executeSQL(createTableSQL);
}

bool history::executeSQL(const QString& sql) {
    char* errMsg = nullptr;
    QByteArray sqlData = sql.toUtf8();

    if (sqlite3_exec(db, sqlData.constData(), nullptr, nullptr, &errMsg) != SQLITE_OK) {
        qDebug() << "SQL error:" << errMsg;
        sqlite3_free(errMsg);
        return false;
    }
    return true;
}

bool history::executeQuery(const QString& sql, QStringList& results) {
    sqlite3_stmt* stmt;
    QByteArray sqlData = sql.toUtf8();

    if (sqlite3_prepare_v2(db, sqlData.constData(), -1, &stmt, nullptr) != SQLITE_OK) {
        qDebug() << "Failed to prepare statement:" << sqlite3_errmsg(db);
        return false;
    }

    results.clear();

    while (sqlite3_step(stmt) == SQLITE_ROW) {
        const unsigned char* text = sqlite3_column_text(stmt, 0);
        results.append(QString::fromUtf8(reinterpret_cast<const char*>(text)));
    }

    sqlite3_finalize(stmt);
    return true;
}

bool history::addWord(const QString& word) {
    if (word.isEmpty()) return false;

    QString sql = QString("INSERT OR REPLACE INTO history (word) VALUES ('%1')")
                  .arg(word);

    return executeSQL(sql);
}

bool history::clearAll() {
    return executeSQL("DELETE FROM history");
}

QStringList history::getAllWords() {
    QStringList words;
    executeQuery("SELECT word FROM history ORDER BY rowid DESC", words);
    return words;
}